require('../../css/sm.css');
require('../../css/sm-extend.css');
require('../../css/style.css');
require('sm');
require('sm-extend');

//SUI
$.init();


// 页面加载事件
module.exports.PageEventBase = function () {
    this.hasResolve = {};
    this.conf = {
        markDom:$('.page-group')
    }
};
module.exports.PageEventBase.prototype = {
    init:function ($page,pageId) {
        var s = this;
        s.resolve(pageId)
            .then($.checkError)
            .then(function (result) {
                $.hidePreloader();
                if(result.code != -1){
                    s.conf.markDom.show();
                    s[pageId].call(null,$page,pageId,{data:result,status:!_.isEmpty(result)});
                }

        });
        $(document).on("pageAnimationStart", function(e, pageId, $page) {
            s.conf.markDom.hide();
            s.resolve(pageId)
                .then($.checkError)
                .then(function (result) {
                    $.hidePreloader();
                    if(result.code != -1){
                        s.conf.markDom.show();
                        s[pageId].call(null,$page,pageId,{data:result,status:!_.isEmpty(result)});
                    }
            });

        });
    },
    getResolveTag:function (pageId) {
        return this.hasResolve[pageId];
    },
    setResolve:function (obj) {
        this.hasResolve = _.assign(this.hasResolve,obj);
    },
    reloadResolve:function (pageId) {
        this.hasResolve = _.set(this.hasResolve,[pageId,'status'],true);
    },
    resolve:function (pageId) {
        var s = this;
        var resolve = s.getResolveTag(pageId);
        if(_.isEmpty(resolve)){
            return $.when('');
        }
        if(resolve.status){
            return $.postAjax(resolve.url,resolve.params)
                .then(function(data){
                    s.hasResolve[pageId].status = false;
                    return $.when(data);
                },function (err) {
                    $.alert('数据加载失败');
            });
        }else{
            return $.when('');
        }
    }
};

// 取本地搜索历史
if(_.isEmpty(store.get('searchHistory'))){
    store.set('searchHistory', []);
}
// 公共方法
$(function () {
    // 打包方法
    $.extend({
        loadTemplate:function ($page,data,template) {
            var promise = $.Deferred();
            $page.find('.load-template').each(function () {
                var templateId = $(this).attr('id');
                var temp = _.template(template[templateId]);
                $(this).html(temp(data[templateId]));
            });
            promise.resolve();
            return promise;
        },
        getParams:function (str) {
            return _.chain(str).thru(function(str) {
                return _.transform(_.split(str.replace(/^\?/,''),'&'), function(result, n) {
                    if(!_.isEmpty(n)){
                        var param = _.split(n,'=');
                        var temp = {};
                        temp[eval('"' + param[0] + '"')] = param[1];
                        result = _.extend(result,temp);
                    }
                    return !_.isEmpty(n);
                }, {});
            }).value();
        },
        getSearch:function (url,params,local) {
            var promise = $.Deferred();
            if(!_.isEmpty(params)){
                $.ajax({
                    url:url,
                    data:params,
                    type:'get',
                    dataType:'json'
                }).done(function(data){
                    promise.resolve(data);
                }).fail(function(err){
                    promise.reject(err);
                });
            }else if(!_.isEmpty(local)){
                promise.resolve({list:local});
            }else{
                $.ajax({
                    url:url,
                    type:'get',
                    dataType:'json'
                }).done(function(data){
                    promise.resolve(data);
                }).fail(function(err){
                    promise.reject(err);
                });
            }
            return promise;
        },
        postAjax:function (url,params) {
            var promise = $.Deferred();
            $.ajax({
                url:url,
                beforeSend:function (xhr) {
                    $.showPreloader();
                },
                type:'post',
                dataType:'json',
                data:params,
                success:function (data) {
                    $.hidePreloader();
                    promise.resolve(data);
                },
                error:function (err) {
                    promise.reject(err);
                }
            });
            return promise;
        },
        checkError:function (data) {
            switch (data.code){
                case -1:
                    $.toast(data.message,1000);
                    setTimeout(function () {
                        window.location.href = '/login.html?return=' + window.location.href;
                    },1000);
                    return $.when(data);
                    break;
                case 1:
                default:
                    return $.when(data);
                    break;
            }
        },
        logout:function (url) {
            $.ajax({
                url:'/app/loginOut.htm',
                type:'post',
                dataType:'json',
                beforeSend:function (xhr) {
                    $.showPreloader();
                },
                success: function(data) {
                    $.hidePreloader();
                    $.alert(data.message,function () {
                        window.location.href = url;
                    });
                }
            });
        }
    });

    $.fn.extend({
        bindGetCode:function () {
            $(this).getcode({
                'time': 60, //自定义时长
                before:function () {
                    var mobile = $(this).prev('input').val();
                    var business = $(this).data('business');
                    if(!_.isEmpty(mobile) && /^(((13[0-9]{1})|(15[0-9]{1})|(18[0-9]{1}))+\d{8})$/.test(mobile)){
                        $(this).addClass('Validation');
                        if(!$(this).hasClass('disabled')){
                            $.ajax({
                                type:'post',
                                dataType:'json',
                                url:$(this).attr('url'),
                                data:{
                                    mobile:mobile,
                                    business:business
                                },
                                beforeSend:function (xhr) {
                                    $.showPreloader('短信发送中...');
                                },
                                success: function(data) {
                                    $.hidePreloader();
                                    if(data.code == 1){
                                        $.toast(data.message);
                                        $(this).parents('.page:visible').find('input[name=yzm]').attr('placeholder','请输入收到的验证码')
                                    }else{
                                        $.toast(data.message);
                                    }
                                }
                            });
                        }
                    }else{
                        $.alert('请输入11位手机号码');
                        $(this).removeClass('Validation');
                    }
                },
                after:function () {
                    $(this).removeClass('Validation');
                }
            });
        }, //取验证码
        showPass:function () {
            $(this).click(function(event) {
                var self = $(this);
                if(self.hasClass('eyes-hide')){
                    self.removeClass('eyes-hide');
                    $(this).siblings('.pw').hide();
                    $(this).siblings('.textP').show();
                    $(this).siblings('.textP').val( $(this).siblings('.pw').val());
                }else{
                    self.addClass('eyes-hide');
                    $(this).siblings('.pw').show();
                    $(this).siblings('.textP').hide();
                    $(this).siblings('.pw').val( $(this).siblings('.textP').val());
                }
            });
        },      //显示密码
        formatSendVal:function (e) {
            return _.chain($(this).find('input[name]')).map(function (input) {
                var name = $(input).attr('name');
                var val = $(input).val();
                if(name !=''){
                    var temp = {};
                    temp[eval('"' + name + '"')] = val;
                    return temp;
                }
            }).thru(function(array) {
                var temp = {};
                _.map(array,function (item) {
                    _.assign(temp,item);
                });
                return temp;
            }).value();
        },      //序列化表单内元素
        ajaxPostData:function (data,call) {
             var defData = {
                 url:$(this).attr('action'),
                 data:$(this).formatSendVal(),
                 type:'post',
                 dataType:'json',
                 beforeSend:function (xhr) {
                     $.showPreloader();
                 },
                 success: function(data) {
                     $.hidePreloader();
                     call(data);
                 }
             };
            $.ajax(_.assign(defData,data));
        } //验证后表单提交
    });
});